package cn.bearspark.happening.provider.dao.buffer;

import cn.bearspark.framework.redis.starter.buffer.list.RedisBaseListBuffer;
import cn.bearspark.happening.provider.dao.key.VoteBufferKeyBuilder;
import cn.bearspark.happening.provider.dao.mapper.VoteOptionMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 投票选项的 id 的缓存器
 *
 * @author f
 */
@Component
public class VoteOptionIdListBuffer extends RedisBaseListBuffer<Integer> {

    /**
     * 投票选项的最多数量，默认为 20 个
     */
    private static final int MAX_VOTE_OPTION_SIZE = 20;

    private final VoteOptionMapper voteOptionMapper;

    private final VoteBufferKeyBuilder voteBufferKeyBuilder;

    public VoteOptionIdListBuffer(RedisTemplate<String, Object> redisTemplate,
                                  VoteOptionMapper voteOptionMapper,
                                  VoteBufferKeyBuilder voteBufferKeyBuilder) {
        super(redisTemplate);
        this.voteOptionMapper = voteOptionMapper;
        this.voteBufferKeyBuilder = voteBufferKeyBuilder;
    }

    /**
     * 获取指定投票的所有选项 id
     *
     * @param voteId 指定的投票 id
     * @return 指定投票的所有选项 id
     */
    public List<Integer> listVoteOptionId(long voteId) {
        return super.range(
                voteBufferKeyBuilder.buildVoteOptionIdListKey(voteId),
                0, MAX_VOTE_OPTION_SIZE,
                () -> voteOptionMapper.listOptionId(voteId)
        );
    }

    @Override
    protected Integer convert(Object obj) {
        return super.objToInteger(obj);
    }

    /**
     * 清理投票选项 id 的缓存
     *
     * @param voteId 指定的投票 id
     */
    public void clean(long voteId) {
        super.clean(voteBufferKeyBuilder.buildVoteOptionIdListKey(voteId));
    }
}
